package com.egene.tw.activity.product;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.egene.tw.api.EgeneApi;
import com.egene.tw.base.BaseRecycleViewFragment;
import com.egene.tw.base.RecycleBaseAdapter;
import com.egene.tw.model.Category;
import com.egene.tw.model.net.ResponseList;
import com.egene.tw.utils.JsonUtil;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.apache.http.Header;

import java.util.List;

@EFragment
public class CategoryListFragment extends BaseRecycleViewFragment {
    public static final String ID = "cid";
    private String mId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if(bundle != null){
            mId = bundle.getString(ID);
        }
    }

    @Override
    protected boolean isNeedListDivider() {
        return true;
    }

    @Override
    protected RecycleBaseAdapter getListAdapter() {
        return new CategoryRecycleAdapter();
    }


    @Override
    protected void sendRequestData() {
        fetchList();
    }

    void fetchList() {
        EgeneApi.getProductList(mId, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                ResponseList<Category> response = JsonUtil.toList(responseBody,
                        new TypeToken<ResponseList<Category>>() {
                        }.getType());
                if (response != null) {
                    System.out.println(response);
                    updateList(response.getData());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                System.out.println(new String(responseBody));
            }
        });
    }

    @Override
    public void loadMore() {
//        super.loadMore();
    }

    @UiThread
    void updateList(List<Category> list) {
        if (mCurrentPage == START_PAGE_INDEX) {
            mAdapter.clear();
        }
        mAdapter.addData(list);
        mAdapter.notifyDataSetChanged();
        executeOnLoadFinish();
    }

    @Override
    protected void onItemClick(View view, int position) {
//        Category category = (Category) mAdapter.getItem(position);
//        Intent intent = new Intent(getActivity(), CategoryInfoActivity_.class);
//        intent.putExtra(CategoryInfoActivity.ID, "" + category.getId());
//        startActivity(intent);
    }
}
